import { useNavigate, useLocation, useRoutes, Navigate } from "react-router-dom"
import React, { useEffect, useState, lazy, ReactNode, Suspense } from 'react'
import { IRouteType } from "@/models/common"
import routes from '@/router/routes'
import util from "@/utils/util"

// 渲染路由
const renderRoutes = (routes: IRouteType[]): IRouteType[] => {
  return routes.map((item: IRouteType) => {
    const route: IRouteType = { meta: item.meta, index: (item.index || false) }
    if (item.path) {
      route.path = item.path
    }
    if (item.element) {
      route.element = <RouterBeforeEach route={item}>{item.element}</RouterBeforeEach>
    }
    if (item.childrens) {
      route.children = renderRoutes(item.childrens)
    }
    if (item.redirect) {
      route.element = <Navigate to={item.redirect} replace />
    }
    return route
  })
}

// 拦截
const RouterBeforeEach = (props: { route: IRouteType, children: React.ReactNode }) => {
  const location = useLocation()
  let share_code = util.getQueryString(location.search, 'share_code') || ''
  const routerKey = location.pathname
  if (props?.route?.meta?.title) {
    document.title = props.route.meta.title;
  }
  
  const isLogin = util.checkIsLogin()
  // if (props?.route?.meta?.needLogin && !share_code) {
  //   if (!isLogin) {
  //     return <Navigate to='/login' replace state={{ from: location }} />
  //   }
  // }

  // if (isLogin && ['/login'].includes(routerKey)) {
  //   return <Navigate to='/' replace />
  // }
  return (
    <>
      {props.children}
    </>
  )
}

export default function Router() {
  // useRoutes API 把路由数组整合为 <Router> <Route path="xx" element="xxx"></Route>等 </Router>的路由组件  直接用于BrowserRouter中
  // console.log(renderRoutes(routes))
  return useRoutes(renderRoutes(routes))
} 